package com.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mh.dao.AssetAccountDao;
import com.mh.dto.vo.R;
import com.mh.dto.vo.TransferVo;
import com.mh.pojo.AssetAccount;
import com.mh.service.AssetAccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 资产账户表(AssetAccount)表服务实现类
 *
 * @author zmh
 * @since 2025-02-08 09:18:49
 */
@Service
@RequiredArgsConstructor
public class AssetAccountServiceImpl extends ServiceImpl<AssetAccountDao, AssetAccount> implements AssetAccountService {

    private final AssetAccountDao assetAccountDao;

    private final RabbitTemplate rabbitTemplate;

    /**
     * 分页查询
     *
     * @param page 查询页数
     * @param size 一页显示条数
     * @return ·
     */
    public R<Page<AssetAccount>> getAllByPage(int page, int size) {
        Page<AssetAccount> assetAccountPage = new Page<>(page, size);
        LambdaQueryWrapper<AssetAccount> queryWrapper = new LambdaQueryWrapper<>();
        //TODO 查询条件定制
        return R.success(assetAccountDao.selectPage(assetAccountPage, queryWrapper));
    }

    /**
     * 根据用户ID获取该用户的所有账户信息
     * @param userId 用户ID
     * @return ·
     */
    @Override
    public R<List<AssetAccount>> getAllByUserId(Integer userId) {
        LambdaQueryWrapper<AssetAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssetAccount::getUserId, userId);
        List<AssetAccount> assetAccounts = assetAccountDao.selectList(queryWrapper);

        if (assetAccounts != null && assetAccounts.size() > 0) {
            return R.success(assetAccounts);
        }
        return R.error("查询失败或用户账户为空");
    }

    /**
     * 转账
     * @param transferVo 转账参数：转出账户ID， 转入账户ID，转账金额
     * @return ·
     */
    @Override
    public R<Boolean> transfer(TransferVo transferVo) {
        AssetAccount outAccount = assetAccountDao.selectById(transferVo.getFromId());
        AssetAccount inAccount = assetAccountDao.selectById(transferVo.getToId());

        if (outAccount != null && inAccount != null) {
            if (outAccount.getBalance() >= transferVo.getAmount()) {
                outAccount.setBalance(outAccount.getBalance() - transferVo.getAmount());
                inAccount.setBalance(inAccount.getBalance() + transferVo.getAmount());
                assetAccountDao.updateById(outAccount);
                assetAccountDao.updateById(inAccount);

                // MQ异步添加加转账记录
                rabbitTemplate.convertAndSend("transfer", transferVo);

                return R.success(true);
            }
            return R.error("余额不足");
        }
        return R.error("账户不存在");
    }
}

